<template>
  <el-card style="max-width: 480px;margin: 200px auto;">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item prop="UserName">
        <el-input v-model="ruleForm.UserName" placeholder="用户"/>
      </el-form-item>
      <el-form-item prop="Password">
        <el-input v-model="ruleForm.Password" type="password"
    placeholder="密码"
    show-password/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'
import { useRoute,useRouter } from 'vue-router'

const route=useRoute();
const router=useRouter();

const Store=useCounterStore();

interface RuleForm {
  UserName: string
  Password: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  UserName: '',
  Password: '',
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  UserName: [
    { required: true, message: '请输入用户', trigger: 'blur' },
  ],
  Password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      axios({
        url:"http://localhost:5028/api/Management/Loging",
        method:"get",
        params:ruleForm
      })
      .then(res=>{
        console.log('登录响应:', res)
        if(res.data.Code==200){
          Store.UserInfo.UserId=res.data.Result.UserId
          Store.UserInfo.UserName=res.data.Result.UserName
          Store.UserInfo.NickName=res.data.Result.NickName
          Store.UserInfo.Token=res.data.Token
          Store.UserInfo.RoleId=res.data.Result.RoleId
          Store.UserInfo.RoleName=res.data.Result.RoleName
          // 将token存储到localStorage，供Axios拦截器使用
          localStorage.setItem('token', res.data.Token);
          console.log('Store:', Store)
          console.log('localStorage token:', localStorage.getItem('token'))
          ElMessage.success(res.data.Message);
          router.push({
            name:'about'
          })
        }
        else{
          ElMessage.error(res.data.Message);
          return;
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>
